package com.andnnl.utils;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

//import org.codehaus.jackson.JsonGenerationException;
//import org.codehaus.jackson.map.JsonMappingException;
//import org.codehaus.jackson.map.ObjectMapper;

public class JsonLib
{

	/**
	 * 把对象或LIST转化成json字符串
	 * @param obj (javabean对象或list)
	 * @return
	 */
	public static String toJson( Object obj)
	{
		if( obj == null )
			return "";
		ObjectMapper objectMapper = new ObjectMapper();
		StringWriter writer = new StringWriter();
        try
		{
			objectMapper.writeValue(writer, obj);
			
		} catch (JsonGenerationException e)
		{
			e.printStackTrace();
		} catch (JsonMappingException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return writer.toString();
	}
	
	/**
	 * json转对象
	 * @param jsonStr
	 * @param classType
	 * @return
	 */
	public static <T> T toObject( String jsonStr, Class classType)
	{
		ObjectMapper mapper = new ObjectMapper();
//		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		mapper.setDateFormat(new MyDateFormat("yyyy-MM-dd HH:mm:ss"));
        try
		{
			T o = (T) mapper.readValue(jsonStr,  classType);
			return o;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return null;
	}

	public static void main(String[] args) {
		Map map=new HashMap();
		map.put("name","namelasdf");
		map.put("date",new Date());
		System.out.println(toJson(map));
	}


}
